package com.mrs.gauss.interfaces.rest;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.shade.com.alibaba.fastjson.JSON;
import com.huawei.shade.com.alibaba.fastjson.JSONObject;
import com.mrs.gauss.common.ErrorCode;
import com.mrs.gauss.exception.BusinessException;
import com.mrs.gauss.interfaces.basicAuth.BasicAuthAccess;
import com.mrs.gauss.interfaces.basicAuth.HttpManager;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * HttpClient自带的HttpDelete方法是不支持上传body的，所以重写delete方法
 * 下载当前用户认证文件
 *
 *
 * @author wubai
 * @version [V100R002C30, 2025-04]
 * @since [OM 1.0]
 */
@Log4j2
public class MrsKeytab {
    //    private static final Logger log = LoggerFactory.getLogger(MrsClusterHosts.class);
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();


    private static final String  DOWNLOAD_URL = "api/v2/permission/users/keytab/download?file_name=";
    private static HttpClient httpClient;

    /**
     * 程序运行入口
     */

    public void getUserKeytab(String user_Name, HttpServletResponse response) {
        log.info("Enter getUserKeytab");

        // 文件UserInfo.properties的路径
        String userFilePath = "./conf/UserInfo.properties";
        InputStream userInfo = null;
        ResourceBundle resourceBundle = null;
        String fileName = null;

        try {
            File file = new File(userFilePath);
            if (!file.exists()) {
                log.error("The user info file doesn't exist.");
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "集群用户属性文件不存在");
            }
//            log.info("Get the web info and user info from file {} ", file);

            userInfo = new BufferedInputStream(new FileInputStream(file));
            resourceBundle = new PropertyResourceBundle(userInfo);

            // 获取用户名
            String userName = resourceBundle.getString("userName");
//            log.info("The user name is : {}.", userName);
            if (userName == null || userName.isEmpty()) {
                log.error("The userName is empty.");
            }

            // 获取用户密码
            String password = resourceBundle.getString("password");
            if (password == null || password.isEmpty()) {
                log.error("The password is empty.");
            }

            String webUrl = resourceBundle.getString("webUrl");
//            log.info("The webUrl is : {}.", webUrl);

            // userTLSVersion是必备的参数，是处理jdk1.6服务端连接jdk1.8服务端时的重要参数，如果用户使用的是jdk1.8该参数赋值为空字符串即可
            String userTLSVersion = "";
            //已登录或session没过期 不再登录
            // 调用firstAccess接口完成登录认证
//            log.info("Begin to get httpclient and first access.");
            BasicAuthAccess authAccess = new BasicAuthAccess();
            httpClient = authAccess.loginAndAccess(webUrl, userName, password, userTLSVersion);
            HttpManager httpManager = new HttpManager();
            String operationName = "";
            String operationUrl = "";

            // 访问Manager接口完成查找getUserKeytab列表
            operationName = "ExportKeytab";
            String EXPORT_URL = "api/v2/permission/users/"+user_Name+"/export_keytab";
            operationUrl = webUrl + EXPORT_URL;
            String responseLineContent = httpManager.sendHttpPostRequestWithString(httpClient, operationUrl,
                    StringUtils.EMPTY, operationName);
            // 调用下载接口
            operationName = "DownloadKeytab";
            JSONObject jsonObj = JSON.parseObject(responseLineContent);
            fileName =jsonObj.getString("fileName");
            if (fileName!=null) {
                String downloadOperationUrl = webUrl + DOWNLOAD_URL + fileName;
                String userHome = System.getProperty("user.home");
                String downloadFilePath = userHome + File.separator + "Downloads" + File.separator;
                httpManager.sendDownloadRequest(httpClient, downloadOperationUrl, operationName,
                        downloadFilePath + fileName, response);
            }else {
                response.setStatus(HttpStatus.NOT_FOUND.value());
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, HttpStatus.NOT_FOUND.toString()+user_Name+"非集群内部用户");
            }

        } catch (FileNotFoundException e) {
            log.error("File not found exception.");
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (userInfo != null) {
                try {
                    userInfo.close();
                } catch (IOException e) {
                    log.error("IOException.");
                }
            }
        }
        // List<Map>
    }
}
